package com.doule.farmerassistant.plan;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.doule.farmerassistant.DeathConfig;
import com.doule.farmerassistant.R;

import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;

/**
 * PlanFragment class.
 * 
 * @author riguang
 * 
 */
public class PlanFragment extends Fragment {
    /**
     * Plan listView.
     */
    private ListView mPlanListView;

    /**
     * PlanDetail table.
     */
    private ArrayList<PlanDetail> mPlanList;

    /**
     * Plan Adapter.
     */
    private PlanAdapter mPlanAdapter;

    /**
     * Authentication token.
     */
    private String mToken;

    /**
     * Login account.
     */
    private String mAccount;

    /**
     * PlanFragment instance.
     */
    private PlanFragment mInstance;

    /**
     * Delete dialog.
     */
    private Dialog dialog;

    /**
     * id which plan delete.
     */
    private String deletePlanID;
    
    /**
     * Progress view.
     */
    private LinearLayout mProgress;
    
    /**
     * LoadPlanTask.
     */
    private LoadPlansTask mLoadPlansTask;
    /**
     * Get PlanDetail table.
     * 
     * @return mPlanList
     */
    public ArrayList<PlanDetail> getPlanList() {
        return mPlanList;
    }

    /**
     * Get plan Adapter.
     * 
     * @return mPlanAdapter
     */
    public PlanAdapter getPlanAdapter() {
        return mPlanAdapter;
    }

    /**
     * Get token.
     * 
     * @return mToken
     */
    public String getToken() {
        return mToken;
    }

    /**
     * Get account.
     * 
     * @return mAccount
     * 
     */
    public String getAccount() {
        return mAccount;
    }

    /**
     * Update Plan listView.
     * 
     */
    public void updateList() {
        mPlanList.clear();
        // mPlanAdapter.notifyDataSetChanged();
        new LoadPlansTask(this, mToken).execute((Void) null);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View v = LayoutInflater.from(getActivity()).inflate(
                R.layout.fragment_plan, null);

        mToken = getActivity().getIntent().getStringExtra("tk");
        mAccount = getActivity().getIntent().getStringExtra("account");
        mInstance = this;
        mPlanListView = (ListView) v.findViewById(R.id.lv_plan);
        mPlanList = new ArrayList<PlanDetail>();
        mPlanAdapter = new PlanAdapter(this, mPlanList);
        mPlanListView.setAdapter(mPlanAdapter);

        mPlanListView.setOnItemLongClickListener(onItemLongClickListener);
        mPlanListView.setVisibility(View.GONE);
        
        mProgress = (LinearLayout) v.findViewById(R.id.progress_view);
        mProgress.setVisibility(View.VISIBLE);
        
        mLoadPlansTask = new LoadPlansTask(this, mToken);
        mLoadPlansTask.execute((Void) null);

        return v;
    }

    /**
     * Item click listener.
     */
    private OnItemLongClickListener onItemLongClickListener = new OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                int position, long arg3) {
            // TODO Auto-generated method stub
            deletePlanID = mPlanList.get(position).getPlanID();
            dialog = new AlertDialog.Builder(mInstance.getActivity())
                    .setIcon(R.drawable.ic_launcher)
                    .setTitle(mInstance.getString(R.string.delete_))
                    .setPositiveButton(mInstance.getString(R.string.delete),
                            onClick)
                    .setNeutralButton(mInstance.getString(R.string.back),
                            onClick).create();
            dialog.show();
            return false;
        }
    };

    /**
     * Dialog Button click.
     */
    private DialogInterface.OnClickListener onClick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface arg0, int which) {
            // TODO Auto-generated method stub
            switch (which) {
            case DialogInterface.BUTTON_POSITIVE:
                // delete
                if (deletePlanID != null) {
                    DeletePlanTask g = new DeletePlanTask(mInstance,
                            deletePlanID, mToken);
                    g.go();
                }
            case DialogInterface.BUTTON_NEUTRAL:
                // break
                dialog.dismiss();
                break;
            default:
                break;
            }
        }
    };
    
    /**
     * LoadPlansTask class.
     * 
     * @author RiGuang
     * 
     */
    final class LoadPlansTask extends AsyncTask<Void, Integer, Boolean> {
        /**
         * Authentication token.
         */
        private String mToken;

        /**
         * PlanFragment context.
         */
        private PlanFragment mContext;

        /**
         * Server url.
         */
        private String mServerUrl;

        /**
         * message list.
         */
        private ArrayList<String> mMsgs = new ArrayList<String>();

        /**
         * Json array.
         */
        private JSONArray jsonArray;

        /**
         * Constructor.
         * 
         * @param context
         *            PlanFragment context.
         * @param token
         *            Authentication token.
         */
        public LoadPlansTask(PlanFragment context, final String token) {
            mContext = context;
            mToken = token;
        }

        /**
         * get the portrait, and set it to the user.
         * 
         * @return true if load plan success.
         */
        private boolean loadPlan() {
            mServerUrl = DeathConfig.getServerUrl();
            if (mToken == null || mServerUrl == null) {
                return true;
            }

            Log.e("LoadMessageTask", "server url: " + mServerUrl);
            HttpPost request = new HttpPost(mServerUrl + "/loadPlan");
            request.setHeader("content-type", "application/json");
            request.setHeader("tk", mToken);

            AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
            try {
                HttpResponse resp = client.execute(request);
                Header head = resp.getFirstHeader("error");
                if (null != head) {
                    String error = head.getValue();
                    Log.e("UserLoginTask", "login error: " + error);
                    return false;
                }

                HttpEntity entity = resp.getEntity();
                String strResult = EntityUtils.toString(entity, "UTF-8");
                parseJson(strResult);
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                client.close();
            }
            return false;
        }

        /**
         * Parser json.
         * 
         * @param jsonStr
         *            jsonString.
         */
        private void parseJson(final String jsonStr) {
            try {
                jsonArray = new JSONArray(jsonStr);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        @Override
        protected Boolean doInBackground(final Void... params) {
            if (loadPlan()) {
                return true;
            }
            return false;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mLoadPlansTask = null;
            
            if (success) {
                mMsgs.clear();
                try {
                    if (jsonArray != null) {
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject obj = jsonArray.getJSONObject(i);
                            PlanDetail p = new PlanDetail(obj);
                            mContext.getPlanList().add(p);
                        }
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                mContext.getPlanAdapter().notifyDataSetChanged();
                
                mPlanListView.setVisibility(View.VISIBLE);
                mProgress.setVisibility(View.GONE);
            }
        }
        
        @Override
        protected void onCancelled() {
            mLoadPlansTask = null;
            mPlanListView.setVisibility(View.VISIBLE);
            mProgress.setVisibility(View.GONE);
        }
    }

}
